<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Base extends Controller_Template {

    /**
     * 是否输出视图
     *
     * @var bool
     */
    public $auto_render = TRUE;

    public $template;
    /**
     * 默认模板目录
     *
     * @var string
     */
    public $template_dir = 'default';
    public $template_view='';

    public $config='';//网站配置
    protected $_css = array();
    protected $_script = array();
    protected $dir='';//控制器父目录
    protected $ctrl='';
    protected $act='';
    protected $view_dir;// view目录=视图模版目录+控制器父目录+控制器目录

    protected $_view_data=array();
    
    protected $_lang=array();

    /**
     * 控制器前置
     */
    public function before()
	{
		parent::before();
       

        /* xss过滤 */

         /* 初始化公共资源地址 */

        $this->config = Kohana::$config->load('config');
        $this->site_url=Kohana::$config->load('config.site_url');
        $this->_lang=$this->config->lang;
        
        View::set_global('lang',  $this->_lang);
         //加载样式 和js
        $this->load_css_script();
	}

    /**
     * 控制器后置
     */
    public function after()
	{
        
        $this->template_compile();
		if ($this->auto_render === TRUE)
		{
			$this->response->body($this->template->render());
		}
		parent::after();
        
	}
    /**
     *  编译模版
     */
    protected function template_compile()
    {
        if (!($this->dir = $this->request->directory()))
        {
            $this->dir = '';
        }

        if (!($this->ctrl = $this->request->controller()))
        {
            $this->ctrl = 'home';
        }

        if (!($this->act = $this->request->action()))
        {
            $this->act = 'index';
        }


        if ( ! headers_sent())
        {
            @header("Content-type: text/html; charset=utf-8");
        }

		if ($this->auto_render === TRUE)
		{
			// Load the template
            //一个控制器对应一个视图目录 action对应视图文件名称 view目录=视图模版目录+控制器父目录+控制器目录
            $this->view_dir= $this->template_dir.(!empty($this->dir)?'/'.str_replace('_','/',$this->dir):'').'/'.str_replace('_','/',$this->ctrl);
            $this->template_view= strtolower($this->view_dir.'/'.$this->act);
			$this->template = View::factory($this->template_view);
		}

        $this->load_view_data();
        

    }
    /**
     * 加载视图变量
     */
    public function load_view_data()
    {
        foreach ( $this->_view_data as $view_key => $view_value)
        {
            $this->template->$view_key=$view_value;
        }

    }

    
    /**
     * 模版赋值
     * @param string $key
     * @param maxied $value
     */
    public function assign($key,$value)
    {
        $this->_view_data[$key]=$value;
    }
    
    

     /**
     * 判断会员或商家登录
     */
    public function check_login()
    {
        if ( ! $this->auth->is_logined()) // 未登录
        {

            if (Request::is_ajax())
            {
                $result = array(
                    'status' => 0,
                    'msg' => '请先登录，才能继续操作！',
                );
                echo json_encode($result);
                exit;
            }

            $this->request->redirect('/login.html?forward='.urlencode($_SERVER['REQUEST_URI']));
        }
        else
        {
            return true;
        }
    }

      /**
     * 获取页面返回地址
     *
     * @param  string  $default
     * @return string
     */
    public function get_back_url($default = NULL)
    {
        $url = isset($_GET['back_url']) ? base64_decode($_GET['back_url']) : $default;
        if (strpos($url, '://') !== FALSE AND ! preg_match('/^http(s)?:\/\/([a-z0-9\-]+\.){0,3}kohana\.com/i', $url)) // 防止钓鱼链接
        {
            return NULL;
        }

        return $url;
    }

    /**
     * 加载css script
     */
    protected function load_css_script()
    {
        View::set_global('styles', implode("\n", array_unique($this->_css)));
        View::set_global('scripts', implode("\n", array_unique($this->_script)));
    }
     /**
     * 添加js脚本
     */
    public function _add_script()
    {
        $args = func_get_args();
        foreach($args as $v)
        {
            $this->_script[] = html::script($v);
        }
    }

    /**
     * 添加css样式表
     */
    public function _add_css()
    {
        $args = func_get_args();
        foreach($args as $v)
        {
            $this->_css[] = html::style($v);
        }
    }


        /**
     * 公共报错页面
     *
     * @param  string  $msg_detail
     * @param  string  $msg_type 默认0，成功1，失败-1
     * @param  array   $links
     * @param  bool    $auto_redirect
     */
    public function show_message($msg_detail, $msg_type = 1, $links = array(), $auto_redirect = FALSE)
    {
      
        if (!headers_sent()) {
            header("Content-type: text/html; charset=utf-8");
        }
        if (count($links) == 0)
        {
            $links[0]['text'] = "上一页";
            $links[0]['href'] = 'javascript:history.go(-1)';
        }
        
        $protocol=parse_url($this->config->site_url, PHP_URL_SCHEME);
        $this->config->site_url=! empty($protocol)?$this->config->site_url:'http://'.$this->config->site_url;
        
        $links[] = array(
            'text' => 'kohana',
            'href' =>$this->config->site_url,
        );
        $this->template->msg_detail = $msg_detail;
        $this->template->msg_type = $msg_type;
        $this->template->links = $links;
        $this->template->default_text = $links[0]['text'];
        $this->template->default_url = $links[0]['href'];
        $this->template->auto_redirect = $auto_redirect;
        $this->template->set_filename('default/message');
        //$this->_add_css('misc/css/user.css');
        exit($this->template->render());
    }

} // End Welcome
